﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Instrument;
using System.IO.Ports;
using System.Configuration;

namespace UI
{
    public partial class SerilPortForm : Form
    {
        public SerilPortForm()
        {
            InitializeComponent();
        }

        private void OKButton_Click(object sender, EventArgs e)
        {
            if(cbbBaudRate.SelectedItem == null || cbbComList.SelectedItem == null || cbbDataBits.SelectedItem == null
                || cbbParity.SelectedItem == null || cbbStopBits.SelectedItem == null)
            {
                DialogResult result = MessageBox.Show("串口配置无效，是否关闭窗口并仍然使用原有配置？", "提示", MessageBoxButtons.YesNo);
                if(result == DialogResult.Yes)
                {
                    Close();
                    return;
                }
                else
                {
                    return;
                }
            }

            var serialPort = SeriPortManage.GetInstance();
            serialPort.PortName = cbbComList.SelectedItem.ToString();
            serialPort.BaudRate = Convert.ToInt32( cbbBaudRate.SelectedItem.ToString());
            serialPort.DataBits = Convert.ToInt32(cbbDataBits.SelectedItem.ToString());
            serialPort.StopBits = (System.IO.Ports.StopBits)Enum.Parse(typeof(System.IO.Ports.StopBits)
                , cbbStopBits.SelectedItem.ToString());
            serialPort.Parity = (Parity)Enum.Parse(typeof(Parity), cbbParity.SelectedItem.ToString());

            Configuration configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configuration.AppSettings.Settings["PortName"].Value = cbbComList.SelectedItem.ToString();
            configuration.AppSettings.Settings["BaudRate"].Value = cbbBaudRate.SelectedItem.ToString();
            configuration.AppSettings.Settings["DataBits"].Value = cbbDataBits.SelectedItem.ToString();
            configuration.AppSettings.Settings["Parity"].Value = cbbParity.SelectedItem.ToString();
            configuration.AppSettings.Settings["StopBits"].Value = cbbStopBits.SelectedItem.ToString();
            configuration.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("AppSettings");

            MessageBox.Show("设置成功");
        }
    }
}
